#! /usr/bin/env python3
# -*-coding: utf-8-*-

"""
Created on Apr 13 2017

@author: Moonkie

@attention: 
    1. 前端界面设计
    2. 综合功能处理
"""

import os
import base64
import time
import random
import sys
import json
import cv2
import shutil
from flask import Flask,request,url_for
from flask import render_template,jsonify
from cnn import detect_face,getChipFeatureData


class Config:
    # SECRET_KEY = os.urandom(30)
    JSON_AS_ASCII = True
    #self
    ROOT = os.path.split(os.path.abspath(__file__))[0]
    # APPLICATION_ROOT = ROOT
    TEMPLATE_FOLER = os.path.join(ROOT,'webforce','templates')
    STATIC_FOLDER = os.path.join(ROOT,'webforce','static')
    DATASETS = os.path.join(ROOT,'datasets')
    IMAGES = os.path.join(DATASETS,'images')
    CHIPS = os.path.join(DATASETS,'faces')
    TEMP = os.path.join(STATIC_FOLDER,'temp')
    ## DEBUG
    # TEMPLATES_AUTO_RELOAD = True

def gen_img_file_name(suffix):
    suffix = 'jpg' if suffix == 'jpeg' else suffix
    name = '-'.join([time.strftime('%Y%m%d%H%M%S'),str(random.randrange(100000))])
    return name+'.'+suffix


sys.path.append(os.path.join(Config.ROOT,'cnn'))
sys.path.append(os.path.join(Config.ROOT,'db'))
sys.path.append(os.path.join(Config.ROOT,'common'))
sys.path.append(os.path.join(Config.ROOT,'svd'))

from svd import KL

if __name__ == '__main__':
    app = Flask(__name__,static_folder=Config.STATIC_FOLDER,template_folder=Config.TEMPLATE_FOLER,root_path=Config.ROOT)
    app.config.from_object(Config)

    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/upload/',methods=['POST'])
    def upload():
        if len(request.form) == 0:
            return jsonify(status=404,msg='Bad Request!')
        image,option = request.files['image'],request.form['option']
        type = image.mimetype.split('/')[-1]
        file_suffix = type.split('/')[-1]
        imgfilename = gen_img_file_name(file_suffix)
        imgfilename = os.path.join(Config.IMAGES,imgfilename)
        image.save(imgfilename)
        
        if option == 'test':
            rsl = detect_face(imgfilename)
            if rsl is 'None' or len(rsl)<10:
                return jsonify(status=200,msg='Non face has been detected in this image.',type='None')
            rsl = json.loads(rsl)
            featurefile = rsl['featurefile']
            face_boxes = getChipFeatureData(featurefile,point='face_boxes')
            source = cv2.imread(imgfilename)
            for box in face_boxes:
                cv2.rectangle(source,(int(box[0]),int(box[1])),(int(box[2]),int(box[3])),(0,255,0),2)
            resultimgpath = os.path.join(Config.TEMP,os.path.basename(imgfilename))
            cv2.imwrite(resultimgpath,source)
            return jsonify(status=200,type='test',src=url_for('static',filename=os.path.join('temp',os.path.basename(resultimgpath)).replace('\\','/')))
        elif option == 'identify':
            kl = KL()
            kl.load()
            rsl = detect_face(imgfilename)
            if rsl is 'None' or len(rsl)<10:
                return jsonify(status=200,msg='Non face has been detected in this image.',type='None')
            rsl = json.loads(rsl)
            faces = rsl['faces']
            imgsrc = []
            for face in faces:
                src = kl.verify(face)
                srcfile = os.path.join(Config.TEMP,str(random.randint(0,1000))+os.path.basename(src))
                shutil.copy(src,srcfile)
                imgsrc.append(url_for('static',filename=os.path.join('temp',os.path.basename(resultimgpath)).replace('\\','/')))
            return jsonify(status=200,type='identify',src=imgsrc)
            
        
        
    app.run(debug=True)
